package com.ja.openchat.ui.contact;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.JsonObject;
import com.ja.openchat.AppViewModelFactory;
import com.ja.openchat.BR;
import com.ja.openchat.BuildConfig;
import com.ja.openchat.R;
import com.ja.openchat.databinding.ActivityContactDetailNewBinding;
import com.ja.openchat.ui.chat.ChatActivity;
import com.ja.openchat.ui.chat.ForwardActivity;
import com.ja.openchat.ui.chat.PreviewWebViewActivity;
import com.ja.openchat.ui.chat.SettingBackgroudActivity;
import com.ja.openchat.ui.contact.search.ChatHistorySearchActivity;
import com.ja.openchat.ui.found.CircleDetailActivity;
import com.ja.openchat.ui.me.MyAlbumFragment;
import com.ja.openchat.ui.me.PersonalDataFragment;
import com.ja.openchat.ui.message.adapter.SimpleFragmentPagerAdapter;
import com.ja.openchat.viewmodels.ContactDetailViewModel;
import com.ja.openchat.views.AttachCopyPopupView;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupAnimation;
import com.lxj.xpopup.enums.PopupPosition;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.zy.openchat.Constants;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.call.CallManager;
import com.zy.openchat.core.model.circle.BlogInfo;
import com.zy.openchat.core.model.circle.BlogListInfo;
import com.zy.openchat.core.model.circle.CircleVisibleType;
import com.zy.openchat.core.model.config.AppConfigInfo;
import com.zy.openchat.core.model.file.FileInfo;
import com.zy.openchat.core.model.group.GroupMemberInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.message.MessageContent;
import com.zy.openchat.core.model.message.MessageInfo;
import com.zy.openchat.core.model.user.MobileContactInfo;
import com.zy.openchat.core.model.user.OrgUserInfo;
import com.zy.openchat.core.model.user.UserFullInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.core.model.user.UserMyInfo;
import com.zy.openchat.util.Common;
import com.zy.openchat.util.ContactUtils;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class ContactDetailActivity extends BaseActivity <ActivityContactDetailNewBinding,ContactDetailViewModel> implements View.OnClickListener, View.OnLongClickListener {

    private ChatInfo mChatInfo;
    private UserFullInfo userFullInfo;
    public UserInfo user;
    private OrgUserInfo orgUserInfo;
    private boolean toShowInvidePath = false;
    private long chatId = 0;
    private boolean blockContact = false;
    private String invidePath;
    private ContactDynamicGridAdapter adapter;

    public static void start(Activity activity, UserInfo user) {
        start(activity, user, 0, false, false);
    }

    //群组聊天或者群组设置页面进入
    public static void start(Activity activity, UserInfo user, long chatId, boolean toShowInvidePath) {
        start(activity, user, chatId, toShowInvidePath, false);
    }

    //群组聊天或者群组设置页面进入
    public static void start(Activity activity, UserInfo user, boolean blockContact) {
        start(activity, user, 0, false, blockContact);
    }

    private static void start(Activity activity, UserInfo user, long chatId, boolean toShowInvidePath, boolean blockContact) {
            Intent intent = new Intent();
            intent.setClass(activity, ContactDetailActivity.class);
            intent.putExtra("user", user);
            intent.putExtra("chatId", chatId);
            intent.putExtra("toShowInvidePath", toShowInvidePath);
            intent.putExtra("blockContact", blockContact);
            activity.startActivity(intent);
    }


    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_contact_detail_new;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public ContactDetailViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(ContactDetailViewModel.class);
    }



    public boolean onLongClick(View view) {
        if (user == null) {
            return false;
        }
        String content = null;
        switch (view.getId()) {
            case R.id.nameText:
                content = user.displayName();
                break;
            case R.id.userNameText:
                content = user.username;
                break;
        }
        if (!TextUtils.isEmpty(content)) {
            new XPopup.Builder(this).hasShadowBg(false).atView(view).popupPosition(PopupPosition.Top).offsetX(view.getWidth() / 2).asCustom(new AttachCopyPopupView(this, content)).show();
        }
        return false;
    }

    @Override
    public void initView() {
        super.initView();
        viewModel.setContext(this);
        binding.toolbar.tvBarTitle.setText(getString(R.string.details_text));
        if (getIntent() != null) {
            user = getIntent().getParcelableExtra("user");
            chatId = getIntent().getLongExtra("chatId", 0);
            toShowInvidePath = getIntent().getBooleanExtra("toShowInvidePath", false);
            blockContact = getIntent().getBooleanExtra("blockContact", false);
        }
        if (user != null && user.id == UserInfo.getUserInfo().id) {
            startContainerActivity(PersonalDataFragment.class.getCanonicalName());
            finish();
        }

        adapter = new ContactDynamicGridAdapter();
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
        binding.recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> a, @NonNull View view, int position) {
                BlogInfo blogInfo = adapter.getItem(position);
                CircleDetailActivity.startDetail(ContactDetailActivity.this,blogInfo.id);
            }
        });
        binding.headerImageView.setTextSize(27);
        //请求原始联系人信息
        requestOrgUserInfo();
        //刷新UI
        resetUI();
        //显示进群方式
        requestInvite();
        if(user!=null&&!user.isDeleteAccount()){
            binding.toolbar.tvOkRight.setVisibility(View.VISIBLE);
            binding.toolbar.tvOkRight.setBackgroundColor(getResources().getColor(R.color.white));
            binding.toolbar.tvOkRight.setTextColor(ContextCompat.getColor(this,R.color.nav_btn_bg));
            binding.toolbar.tvOkRight.setText(getString(R.string.edit_text));
            binding.toolbar.tvOkRight.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(mChatInfo!=null){
                        EditUserProfileActivity.start(ContactDetailActivity.this,user,mChatInfo,blockContact);
                    }
                }
            });
        }
        binding.toolbar.ivBarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        requestChatInfo(new OnContactChatInfoListener() {
            @Override
            public void onResult(ChatInfo chatInfo) {
                mChatInfo = chatInfo;
                initFragments(mChatInfo);
                resetUI();
            }
        });

        if(user!=null){
            binding.userStatusStr.setText(user.getUserStatusLable());
        }

        binding.addLayout.setOnClickListener(this);
        binding.sendMsgLayout.setOnClickListener(this);
        binding.voiceCallBtn.setOnClickListener(this);
        binding.videoCallBtnBtn.setOnClickListener(this);
        binding.moreHandleBtn.setOnClickListener(this);
        binding.muteVoiceBtn.setOnClickListener(this);
        binding.pingbiLayout.setOnClickListener(this);
        binding.nameText.setOnLongClickListener(this);
        binding.userNameText.setOnLongClickListener(this);
        binding.groupAnnLayout.setOnClickListener(this);
        AppConfigInfo configInfo = AppConfigInfo.getAppWithoutLoginConfigInfo();
        if(configInfo!=null&&!configInfo.can_see_blog){
            binding.groupAnnLayout.setVisibility(View.GONE);
        }
        if(chatId == TelegramManager.TG_USERID_SYSTEM_NOTICE){
            binding.sexTagIv.setVisibility(View.GONE);
            binding.userIntroView.setVisibility(View.GONE);
        }else{
            loadUserCircleInfo();
        }
        if(BuildConfig.ShowLocal_ChatRecord){
            binding.tablayout.setVisibility(View.VISIBLE);
            binding.viewPager.setVisibility(View.VISIBLE);
        }else{
            binding.tablayout.setVisibility(View.GONE);
            binding.viewPager.setVisibility(View.GONE);
        }
    }

    private void loadUserCircleInfo(){
        if(user==null){
            return;
        }
        TelegramManager.getTelegramManager().getUserInfoEx(this,user.id, new TgResultBlock<UserMyInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, UserMyInfo obj) {
                if(obj!=null){
                    binding.sexTagIv.setImageResource(obj.gender == 0?R.mipmap.nearby_man:R.mipmap.nearby_women);
                    binding.userAgeStr.setVisibility(View.VISIBLE);
                    binding.userAgeStr.setText(String.format(getString(R.string.age_year_old),Common.getAgeByBirth(obj.birth)));
                    binding.userAddressStr.setVisibility(View.VISIBLE);
                    binding.userAddressStr.setText(obj.getAddress());
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
        TelegramManager.getTelegramManager().getCircleHistory(this, new CircleVisibleType(user.id), 0, 3, new TgResultBlock<BlogListInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, BlogListInfo obj) {
                if (obj != null&&!Common.isEmpty(obj.blogs)) {
                    adapter.setNewInstance(obj.blogs);
                } else {

                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    public void notifyMediaInfo(TelegramManager.EUser_TgEvent tgEvent,FileInfo fileInfo,String blogId){
        if(fileInfo==null||TextUtils.isEmpty(blogId)||Common.isEmpty(adapter.getData())){
            return;
        }
        for(int i = 0; i<adapter.getData().size(); i++){
            BlogInfo blogInfo = adapter.getItem(i);
            boolean isVideoDownedd = blogInfo.isVideoDownloadEnough();
            if(blogId.equals(String.valueOf(blogInfo.id))){
                switch (tgEvent) {
                    case EUser_Td_Message_Photo_Ok:
                        blogInfo.updatePhotoFile(fileInfo);
                        break;
                    case EUser_Td_Message_Video_Ok:
                        blogInfo.updateVideoFile(fileInfo);
                        break;
                }
                if(tgEvent == TelegramManager.EUser_TgEvent.EUser_Td_Message_Video_Ok&&isVideoDownedd){
                    return;
                }
                adapter.notifyItemChanged(i);
                break;
            }

        }
    }

    private void requestChatInfo(OnContactChatInfoListener listener){
        ChatInfo chatInfo = null;
        if(chatId>0){
            chatInfo = TelegramManager.getTelegramManager().getTgData().chatInfo(chatId);
        }
        if(chatInfo!=null){
            listener.onResult(chatInfo);
        }else if(user!=null){
            TelegramManager.getTelegramManager().createPrivateChat(this, user.id, new TgResultBlock<ChatInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                    if (obj != null) {
                        listener.onResult(obj);
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                }
            });
        }else{
            listener.onResult(chatInfo);
        }
    }




    private void initFragments(ChatInfo chatInfo){
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(ContactDetailChildFragment.newInstance(0,chatInfo));
        fragments.add(ContactDetailChildFragment.newInstance(1,chatInfo));
        fragments.add(ContactDetailChildFragment.newInstance(2,chatInfo));
        fragments.add(ContactDetailChildFragment.newInstance(3,chatInfo));
        fragments.add(ContactDetailChildFragment.newInstance(4,chatInfo));
        fragments.add(ContactDetailChildFragment.newInstance(5,chatInfo));
        SimpleFragmentPagerAdapter fragmentAdater = new  SimpleFragmentPagerAdapter(getSupportFragmentManager(),fragments,new String[]{
                getString(R.string.media_text),
                getString(R.string.file_text),getString(R.string.voice_text),getString(R.string.link_text),"GIF",getString(R.string.group_text)});
        binding.viewPager.setAdapter(fragmentAdater);
        binding.viewPager.setOffscreenPageLimit(fragments.size());
        binding.tablayout.setupWithViewPager(binding.viewPager);
        syncUserFullInfo();
    }

    public void resetUI() {
        if (user != null) {
            MobileContactInfo contactInfo = ContactUtils.getIntance().getContactInfoByUserId(user.id);
            if(contactInfo!=null&&!TextUtils.isEmpty(contactInfo.phone_number)){
                binding.userMobileValue.setText(Common.formatPhoneNumber("86"+contactInfo.phone_number));
                binding.userMobileLayout.setVisibility(View.VISIBLE);
            }else{
                binding.userMobileLayout.setVisibility(View.GONE);
            }
            binding.headerImageView.showUser(user);
            if (blockContact) {
                binding.userNameLayout.setVisibility(View.VISIBLE);
                binding.userNameText.setText("@******");
            } else {
                if (!StringUtils.isEmpty(user.username)) {
                    binding.userNameLayout.setVisibility(View.VISIBLE);
                    binding.userNameText.setText("@" + user.username);
                } else {
                    binding.userNameLayout.setVisibility(View.GONE);
                    binding.userNameText.setText(" ");
                }
            }

            if (user.is_contact) {
                if (orgUserInfo != null) {
                    binding.nameText.setText(orgUserInfo.displayName());
                    if (!orgUserInfo.displayName().equals(user.displayName())) {
//                        remarkText.setText(user.displayName());
                    } else {
//                        remarkText.setText("");
                    }
                } else {
                    binding.nameText.setText(user.displayName());
//                    remarkText.setText("");
                }
            } else {
                binding.nameText.setText(user.displayName());
//                remarkText.setText("");
            }

            if(BuildConfig.ShowLocal_VoiceChat){
                binding.voiceCallBtn.setVisibility(View.VISIBLE);
                binding.videoCallBtnBtn.setVisibility(View.VISIBLE);
            }else{
                binding.voiceCallBtn.setVisibility(View.GONE);
                binding.videoCallBtnBtn.setVisibility(View.GONE);
            }

            //操作菜单
            if (blockContact) {
                binding.addLayout.setVisibility(View.GONE);
                binding.pingbiLayout.setVisibility(View.GONE);
                binding.sendMsgLayout.setVisibility(View.GONE);
            } else {
                boolean isShowUserNameView = false;
                binding.pingbiLayout.setVisibility(View.VISIBLE);
                binding.addLayout.setVisibility(View.VISIBLE);
                binding.sendMsgLayout.setVisibility(View.VISIBLE);
                if (user.is_contact) {
                    isShowUserNameView = true;
                    binding.pingbiLayout.setVisibility(View.GONE);
                    binding.addLayout.setVisibility(View.GONE);
                } else {
                    if (!canAddFriend()) {
                        isShowUserNameView = true;
                        binding.pingbiLayout.setVisibility(View.GONE);
                        binding.addLayout.setVisibility(View.GONE);
                    }
                }
                if(!isShowUserNameView){
                    binding.userMobileLayout.setVisibility(View.GONE);
                    binding.userNameLayout.setVisibility(View.GONE);
                }
                if (!canSendMsg()) {
//                    binding.voiceCallBtn.setVisibility(View.GONE);
//                    binding.videoCallBtnBtn.setVisibility(View.GONE);
//                    binding.sendMsgLayout.setVisibility(View.GONE);
                }
            }
        }
        if(mChatInfo!=null){
            binding.muteVoiceBtn.setActivated(mChatInfo.default_disable_notification);
        }
        if(userFullInfo!=null){
            binding.pingbiLayout.setText(userFullInfo.is_blocked?getString(R.string.person_has_been_blocked):getString(R.string.block_this_person_text));
        }

    }

    private void syncUserFullInfo() {
        if(mChatInfo==null){
            return;
        }
        TelegramManager.getTelegramManager().requestContactFullInfo(this, mChatInfo.id, new TgResultBlock<UserFullInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, UserFullInfo obj) {
                if (obj != null) {
                    userFullInfo = obj;
                    resetUI();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }

    public void requestOrgUserInfo() {
        if (user != null) {
            TelegramManager.getTelegramManager().requestOrgContactInfo(this, user.id, new TgResultBlock<OrgUserInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, OrgUserInfo obj) {
                    if (obj != null) {
                        orgUserInfo = obj;
                        resetUI();
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                }
            });
        }
    }


    private void blockUser() {
        if(mChatInfo==null||userFullInfo==null){
            return;
        }
        showProgress();
        TelegramManager.getTelegramManager().blockUser(this, mChatInfo.id, !userFullInfo.is_blocked, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                    resetUI();
                } else {
                    userFullInfo.is_blocked = !userFullInfo.is_blocked;
                    resetUI();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
                resetUI();
            }
        });
    }

    private void requestInvite() {
        if (chatId != 0 && toShowInvidePath) {
            TelegramManager.getTelegramManager().getGroupMember(this, chatId, user.id, new TgResultBlock<GroupMemberInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, GroupMemberInfo obj) {
                    if (obj != null && obj.inviter_user_id != 0) {
                        UserInfo invideUser = TelegramManager.getTelegramManager().getTgData().contactInfo(obj.inviter_user_id);
                        if (invideUser != null) {
                            resetInvidePath(invideUser);
                        } else {
                            requestInvideUserInfo(obj.inviter_user_id);
                        }
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {

                }
            });
        }
    }

    private void requestInvideUserInfo(long invideUserId) {
        TelegramManager.getTelegramManager().requestContactInfo(this, invideUserId, new TgResultBlock<UserInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, UserInfo obj) {
                if (obj != null) {
                    resetInvidePath(obj);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    private OrgUserInfo loginOrgUserInfo;
    private void getLoginOrgUserInfo(){
        TelegramManager.getTelegramManager().requestOrgContactInfo(this, UserInfo.getUserInfo().id, new TgResultBlock<OrgUserInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, OrgUserInfo obj) {
                loginOrgUserInfo = obj;
                resetUI();
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }

    private boolean canAddFriend() {
        if(loginOrgUserInfo!=null&&loginOrgUserInfo.isInternal){
            return true;
        }
        AppConfigInfo info = AppConfigInfo.getAppConfigInfo();
        if (info != null) {
            if (info.onlyWhiteAddFriend) {
                return orgUserInfo != null ? orgUserInfo.isInternal : false;
            }
        }
        return true;
    }

    private boolean canSendMsg() {
        if (user != null) {
            return user.canSendMsg();
        }
        return false;
    }

    private void resetInvidePath(UserInfo inviteUser) {
        if (inviteUser.id == UserInfo.getUserInfo().id) {
            invidePath = getString(R.string.you_invite_to_group);
        } else if(user!=null&&user.id==inviteUser.id){
            invidePath = getString(R.string.join_via_invite_link);
        }else {
            invidePath = String.format(getString(R.string.invited_join_group), inviteUser.displayName());
        }
//        inviteText.setText(invidePath);
        resetUI();
    }

    private void clickAdd() {//添加好友
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(R.string.dialog_title_tip).setMessage(String.format(getString(R.string.want_add_somebody_as_friend), user.displayName()));
        dialog.setPositiveButton(R.string.dialog_ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        doAddContact();
                    }
                });
        dialog.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void doAddContact() {
        showProgress();
        TelegramManager.getTelegramManager().addContact(this, user, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                } else {
                    ToastUtils.showShort(String.format(getString(R.string.somebody_added_friends), user.displayName()));
                    TelegramManager.getTelegramManager().sendBeFriendMessage(ContactDetailActivity.this, user.id, new TgResultBlock<TgResponse>() {
                        @Override
                        public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                        }

                        @Override
                        public void onTimeout(Map<String, Object> request) {
                        }
                    });
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    private void clickDelete() {//删除好友
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(R.string.dialog_title_tip).setMessage(String.format(getString(R.string.want_delete_friend), user.displayName()));
        dialog.setPositiveButton(R.string.dialog_ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        doDeleteContact();
                    }
                });
        dialog.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void doDeleteContact() {
        showProgress();
        TelegramManager.getTelegramManager().deleteContact(this, user.id, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                } else {
                    ToastUtils.showShort(String.format(getString(R.string.removed_friends_list), user.displayName()));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.addLayout://添加好友
                if (user != null) {
                    clickAdd();
                }
                break;
//            case R.id.deleteLayout://删除好友
//                if (user != null) {
//                    clickDelete();
//                }
//                break;
            case R.id.sendMsgLayout://发送消息
                if(!canSendMsg()){
                    ToastUtils.showShort(getString(R.string.other_not_friend_first_add));
                    return;
                }
                if (user != null) {
                    TelegramManager.getTelegramManager().createPrivateChat(this, user.id, new TgResultBlock<ChatInfo>() {
                        @Override
                        public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                            if (obj != null) {
                                ChatActivity.startActivity(ContactDetailActivity.this, obj);
                            }
                        }

                        @Override
                        public void onTimeout(Map<String, Object> request) {
                        }
                    });
                }
                break;
            case R.id.voice_call_btn://音视频通话
                if(!canSendMsg()){
                    ToastUtils.showShort(getString(R.string.other_not_friend_first_add));
                    return;
                }
                if (user != null) {
                    CallManager.startC2CNewCall(this, user,false);
                }
                break;
            case R.id.video_call_btn_btn:
                if(!canSendMsg()){
                    ToastUtils.showShort(getString(R.string.other_not_friend_first_add));
                    return;
                }
                if (user != null) {
                    CallManager.startC2CNewCall(this, user,true);
                }
                break;
            case R.id.mute_voice_btn:
                muteSwitchClick();
                break;
            case R.id.more_handle_btn:
                if(mChatInfo==null){
                    return;
                }
                String[] titles;
                OnSelectListener selectListener;
                if (mChatInfo.id == TelegramManager.TG_USERID_SYSTEM_NOTICE) {
                    titles = new String[]{getString(R.string.set_current_chat_bg),getString(R.string.complaint_text), getString(R.string.find_chat_content)};
                    selectListener = new OnSelectListener() {
                        @Override
                        public void onSelect(int position, String text) {
                            switch (position){
                                case 0:
                                    if(mChatInfo!=null){
                                        SettingBackgroudActivity.start(ContactDetailActivity.this, mChatInfo);
                                    }
                                    break;
                                case 1:
                                    PreviewWebViewActivity.loadUrl(ContactDetailActivity.this, getString(R.string.complaint_text), Constants.KHostEReport);
                                    break;
                                case 2:
                                    ChatHistorySearchActivity.start(ContactDetailActivity.this, mChatInfo,-1);
                                    break;
                            }
                        }
                    };
                }else{
                    titles = new String[]{getString(R.string.recommend_friends)
                            ,getString(R.string.start_group_chat)
                            ,getString(R.string.turn_on_private_chat)
                            ,getString(R.string.set_current_chat_bg),getString(R.string.complaint_text), getString(R.string.find_chat_content)};
                    selectListener = new OnSelectListener() {
                        @Override
                        public void onSelect(int position, String text) {
                            switch (position){
                                case 0:
                                    if (user != null){
                                        MessageInfo messageInfo = new MessageInfo();
                                        MessageContent content = new MessageContent();
                                        MobileContactInfo contactInfo = new MobileContactInfo();
                                        contactInfo.first_name = user.first_name;
                                        contactInfo.last_name = user.last_name;
                                        contactInfo.user_id = user.id;
                                        contactInfo.phone_number = user.phone_number;
                                        content.contact = contactInfo;
                                        messageInfo.content = content;
                                        messageInfo.messageType = TelegramManager.MessageType.MessageType_Contact;

                                        Intent intent = new Intent(ContactDetailActivity.this, ForwardActivity.class);
                                        intent.putExtra("message", messageInfo);
                                        startActivity(intent);
                                        finish();
                                    }
                                    break;
                                case 1:
                                    if(!canSendMsg()){
                                        ToastUtils.showShort(getString(R.string.other_not_friend_first_add));
                                        return;
                                    }
                                    if(mChatInfo!=null){
                                        ContactChooseActivity.startWithCreateSuperGroup(ContactDetailActivity.this, mChatInfo.id);
                                    }
                                    break;
                                case 2:
                                    if(!canSendMsg()){
                                        ToastUtils.showShort(getString(R.string.other_not_friend_first_add));
                                        return;
                                    }
                                    startSecretChat();
                                    break;
                                case 3:
                                    if(!canSendMsg()){
                                        ToastUtils.showShort(getString(R.string.other_not_friend_first_add));
                                        return;
                                    }
                                    if(mChatInfo!=null){
                                        SettingBackgroudActivity.start(ContactDetailActivity.this, mChatInfo);
                                    }
                                    break;
                                case 4:
                                    PreviewWebViewActivity.loadUrl(ContactDetailActivity.this, getString(R.string.complaint_text), Constants.KHostEReport);
                                    break;
                                case 5:
                                    ChatHistorySearchActivity.start(ContactDetailActivity.this, mChatInfo,-1);
                                    break;

                            }
                        }
                    };
                }
                new XPopup.Builder(this)
                        .atView(view)
                        .offsetY(0)
                        .hasShadowBg(false)
                        .popupAnimation(PopupAnimation.NoAnimation)
                        .asAttachList(titles, null, selectListener).show();
                break;
            case R.id.pingbiLayout:
                blockUser();
                break;
            case R.id.group_ann_layout:
                Bundle bundle = new Bundle();
                bundle.putLong("userId", user.id);
                viewModel.startContainerActivity(MyAlbumFragment.class.getCanonicalName(), bundle);
                break;
        }
    }

    private void startSecretChat(){
        if(mChatInfo == null){
            return;
        }
        showProgress();
        TelegramManager.getTelegramManager().createNewSecretChat(this, mChatInfo.userId(), new TgResultBlock<ChatInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                hideProgress();
                if (obj!=null) {
                    ChatActivity.startActivity(ContactDetailActivity.this, obj);
                    finish();
                } else {
                    showErrorTip(getString(R.string.request_error));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    private void muteSwitchClick() {
        if(mChatInfo==null){
            return;
        }
        showProgress();
        TelegramManager.getTelegramManager().toggleChatDisableNotification(this, mChatInfo.id, !mChatInfo.default_disable_notification, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                    resetUI();
                } else {
                    syncChatInfo();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
                resetUI();
            }
        });
    }

    private void syncChatInfo() {
        if (mChatInfo != null) {
            ChatInfo chat = TelegramManager.getTelegramManager().getTgData().chatInfo(mChatInfo.id);
            if (chat != null) {
                mChatInfo = chat;
            }
        }
        resetUI();
    }


    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }
}